

<!DOCTYPE html>
<!--[if IE]><![endif]-->
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>isMounted is an Antipattern - React Blog</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta property="og:title" content="isMounted is an Antipattern - React Blog">
  <meta property="og:type" content="article">
  <meta property="og:url" content="https://facebook.github.io/react/blog/2015/12/16/ismounted-antipattern.html">
  <meta property="og:image" content="https://facebook.github.io/react/img/logo_og.png">
  <meta property="og:description" content="As we move closer to officially deprecating isMounted, it&#39;s worth understanding why the function is an antipattern, and how to write code without the isMounted function.
">
  <meta property="fb:app_id" content="623268441017527">

  <link rel="shortcut icon" href="/react/favicon.ico">
  <link rel="alternate" type="application/rss+xml" title="React" href="https://facebook.github.io/react/feed.xml">

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/docsearch.js/1/docsearch.min.css" />
  <link rel="stylesheet" href="/css/syntax.css">
  <link rel="stylesheet" href="/css/codemirror.css">
  <link rel="stylesheet" href="/css/react.css">

  <script src="//use.typekit.net/vqa1hcx.js"></script>
  <script>try{Typekit.load();}catch(e){}</script>

  <!--[if lte IE 8]>
  <script src="/js/html5shiv.min.js"></script>
  <script src="/js/es5-shim.min.js"></script>
  <script src="/js/es5-sham.min.js"></script>
  <![endif]-->
  <script type="text/javascript" src="https://cdn.jsdelivr.net/docsearch.js/1/docsearch.min.js"></script>
  <script src="/js/codemirror.js"></script>
  <script src="/js/javascript.js"></script>
  <script src="/js/xml.js"></script>
  <script src="/js/jsx.js"></script>
  <script src="/js/react.js"></script>
  <script src="/js/react-dom.js"></script>
  <script src="/js/babel.min.js"></script>
  <script src="/js/live_editor.js"></script>
</head>
<body>

  <div class="container">

    <div class="nav-main">
  <div class="wrap">
    <a class="nav-home" href="/react/">
      <img class="nav-logo" src="/img/logo.svg" width="36" height="36">
      React
    </a>
    <div class="nav-lists">
      <ul class="nav-site nav-site-internal">
        <li><a href="/react/docs/hello-world.html">Docs</a></li>
        <li><a href="/react/tutorial/tutorial.html">Tutorial</a></li>
        <li><a href="/react/community/support.html">Community</a></li>
        <li><a href="/react/blog/" class="active">Blog</a></li>
        <li class="nav-site-search">
          <input id="algolia-doc-search" type="text" placeholder="Search docs..." />
        </li>
      </ul>
      <ul class="nav-site nav-site-external">
        <li><a href="https://github.com/facebook/react">GitHub</a></li>
        <li><a href="https://github.com/facebook/react/releases">v16.0.0-alpha.3</a></li>
      </ul>
    </div>
  </div>
</div>


    <section class="content wrap blogContent">

  <div class="inner-content">
    

<h1>

  isMounted is an Antipattern

</h1>

<p class="meta">
  December 16, 2015
  by
  
    
      <a href="http://www.jimsproch.com">Jim Sproch</a>
    
    
  
</p>

<hr>

<div class="post">
  <p>As we move closer to officially deprecating isMounted, it&#39;s worth understanding why the function is an antipattern, and how to write code without the isMounted function.</p>

<p>The primary use case for <code>isMounted()</code> is to avoid calling <code>setState()</code> after a component has unmounted, because calling <code>setState()</code> after a component has unmounted will emit a warning. The “setState warning” exists to help you catch bugs, because calling <code>setState()</code> on an unmounted component is an indication that your app/component has somehow failed to clean up properly. Specifically, calling <code>setState()</code> in an unmounted component means that your app is still holding a reference to the component after the component has been unmounted - which often indicates a memory leak!</p>

<p>To avoid the error message, people often add lines like this:</p>
<div class="highlight"><pre><code class="language-js" data-lang="js"><span class="k">if</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">isMounted</span><span class="p">())</span> <span class="p">{</span> <span class="c1">// This is bad.</span>
  <span class="k">this</span><span class="p">.</span><span class="nx">setState</span><span class="p">({...});</span>
<span class="p">}</span>
</code></pre></div>
<p>Checking <code>isMounted</code> before calling <code>setState()</code> does eliminate the warning, but it also defeats the purpose of the warning, since now you will never get the warning (even when you should!)</p>

<p>Other uses of <code>isMounted()</code> are similarly erroneous; using <code>isMounted()</code> is a code smell because the only reason you would check is because you think you might be holding a reference after the component has unmounted.</p>

<p>An easy migration strategy for anyone upgrading their code to avoid <code>isMounted()</code> is to track the mounted status yourself.  Just set a <code>_isMounted</code> property to true in <code>componentDidMount</code> and set it to false in <code>componentWillUnmount</code>, and use this variable to check your component&#39;s status.</p>

<p>An optimal solution would be to find places where <code>setState()</code> might be called after a component has unmounted, and fix them. Such situations most commonly occur due to callbacks, when a component is waiting for some data and gets unmounted before the data arrives. Ideally, any callbacks should be canceled in <code>componentWillUnmount</code>, prior to unmounting.</p>

<p>For instance, if you are using a Flux store in your component, you must unsubscribe in <code>componentWillUnmount</code>:</p>
<div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kr">class</span> <span class="nx">MyComponent</span> <span class="kr">extends</span> <span class="nx">React</span><span class="p">.</span><span class="nx">Component</span> <span class="p">{</span>
  <span class="nx">componentDidMount</span><span class="p">()</span> <span class="p">{</span>
    <span class="nx">mydatastore</span><span class="p">.</span><span class="nx">subscribe</span><span class="p">(</span><span class="k">this</span><span class="p">);</span>
  <span class="p">}</span>
  <span class="nx">render</span><span class="p">()</span> <span class="p">{</span>
    <span class="p">...</span>
  <span class="p">}</span>
  <span class="nx">componentWillUnmount</span><span class="p">()</span> <span class="p">{</span>
<span class="hll">    <span class="nx">mydatastore</span><span class="p">.</span><span class="nx">unsubscribe</span><span class="p">(</span><span class="k">this</span><span class="p">);</span>
</span>  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div>
<p>If you use ES6 promises, you may need to wrap your promise in order to make it cancelable.</p>
<div class="highlight"><pre><code class="language-js" data-lang="js"><span class="kr">const</span> <span class="nx">cancelablePromise</span> <span class="o">=</span> <span class="nx">makeCancelable</span><span class="p">(</span>
  <span class="k">new</span> <span class="nx">Promise</span><span class="p">(</span><span class="nx">r</span> <span class="o">=&gt;</span> <span class="nx">component</span><span class="p">.</span><span class="nx">setState</span><span class="p">({...}}))</span>
<span class="p">);</span>

<span class="nx">cancelablePromise</span>
  <span class="p">.</span><span class="nx">promise</span>
  <span class="p">.</span><span class="nx">then</span><span class="p">(()</span> <span class="o">=&gt;</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s1">&#39;resolved&#39;</span><span class="p">))</span>
  <span class="p">.</span><span class="k">catch</span><span class="p">((</span><span class="nx">reason</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s1">&#39;isCanceled&#39;</span><span class="p">,</span> <span class="nx">reason</span><span class="p">.</span><span class="nx">isCanceled</span><span class="p">));</span>

<span class="nx">cancelablePromise</span><span class="p">.</span><span class="nx">cancel</span><span class="p">();</span> <span class="c1">// Cancel the promise</span>
</code></pre></div>
<p>Where <code>makeCancelable</code> is <a href="https://github.com/facebook/react/issues/5465#issuecomment-157888325">defined by @istarkov</a> as:</p>
<div class="highlight"><pre><code class="language-js" data-lang="js"><span class="kr">const</span> <span class="nx">makeCancelable</span> <span class="o">=</span> <span class="p">(</span><span class="nx">promise</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="kd">let</span> <span class="nx">hasCanceled_</span> <span class="o">=</span> <span class="kc">false</span><span class="p">;</span>

  <span class="kr">const</span> <span class="nx">wrappedPromise</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Promise</span><span class="p">((</span><span class="nx">resolve</span><span class="p">,</span> <span class="nx">reject</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
    <span class="nx">promise</span><span class="p">.</span><span class="nx">then</span><span class="p">((</span><span class="nx">val</span><span class="p">)</span> <span class="o">=&gt;</span>
      <span class="nx">hasCanceled_</span> <span class="o">?</span> <span class="nx">reject</span><span class="p">({</span><span class="nx">isCanceled</span><span class="o">:</span> <span class="kc">true</span><span class="p">})</span> <span class="o">:</span> <span class="nx">resolve</span><span class="p">(</span><span class="nx">val</span><span class="p">)</span>
    <span class="p">);</span>
    <span class="nx">promise</span><span class="p">.</span><span class="k">catch</span><span class="p">((</span><span class="nx">error</span><span class="p">)</span> <span class="o">=&gt;</span>
      <span class="nx">hasCanceled_</span> <span class="o">?</span> <span class="nx">reject</span><span class="p">({</span><span class="nx">isCanceled</span><span class="o">:</span> <span class="kc">true</span><span class="p">})</span> <span class="o">:</span> <span class="nx">reject</span><span class="p">(</span><span class="nx">error</span><span class="p">)</span>
    <span class="p">);</span>
  <span class="p">});</span>

  <span class="k">return</span> <span class="p">{</span>
    <span class="nx">promise</span><span class="o">:</span> <span class="nx">wrappedPromise</span><span class="p">,</span>
    <span class="nx">cancel</span><span class="p">()</span> <span class="p">{</span>
      <span class="nx">hasCanceled_</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span>
    <span class="p">},</span>
  <span class="p">};</span>
<span class="p">};</span>
</code></pre></div>
<p>As an added bonus for getting your code cleaned up early, getting rid of <code>isMounted()</code> makes it one step easier for you to upgrade to ES6 classes, where using <code>isMounted()</code> is already prohibited.  Happy coding!</p>

</div>


  <div class="fb-like" data-send="true" data-width="650" data-show-faces="false"></div>


  </div>
  <div class="nav-docs nav-blog">
  <div class="nav-docs-section">
    <h3>Recent posts</h3>
    <ul>
      
        <li><a href="/react/blog/2016/11/16/react-v15.4.0.html">React v15.4.0</a></li>
      
        <li><a href="/react/blog/2016/09/28/our-first-50000-stars.html">Our First 50,000 Stars</a></li>
      
        <li><a href="/react/blog/2016/08/05/relay-state-of-the-state.html">Relay: State of the State</a></li>
      
        <li><a href="/react/blog/2016/07/22/create-apps-with-no-configuration.html">Create Apps with No Configuration</a></li>
      
        <li><a href="/react/blog/2016/07/13/mixins-considered-harmful.html">Mixins Considered Harmful</a></li>
      
        <li><a href="/react/blog/2016/07/11/introducing-reacts-error-code-system.html">Introducing React's Error Code System</a></li>
      
        <li><a href="/react/blog/2016/04/08/react-v15.0.1.html">React v15.0.1</a></li>
      
        <li><a href="/react/blog/2016/04/07/react-v15.html">React v15.0</a></li>
      
        <li><a href="/react/blog/2016/03/29/react-v0.14.8.html">React v0.14.8</a></li>
      
        <li><a href="/react/blog/2016/03/16/react-v15-rc2.html">React v15.0 Release Candidate 2</a></li>
      
      <li><a href="/react/blog/all.html">All posts ...</a></li>
    </ul>
  </div>
</div>

</section>


    <footer class="nav-footer">
  <section class="sitemap">
    <a href="/react/" class="nav-home">
    </a>
    <div>
      <h5><a href="/react/docs/">Docs</a></h5>
      <a href="/react/docs/hello-world.html">Quick Start</a>
      <a href="/react/docs/thinking-in-react.html">Thinking in React</a>
      <a href="/react/tutorial/tutorial.html">Tutorial</a>
      <a href="/react/docs/jsx-in-depth.html">Advanced Guides</a>
    </div>
    <div>
      <h5><a href="/react/community/support.html">Community</a></h5>
      <a href="http://stackoverflow.com/questions/tagged/reactjs" target="_blank">Stack Overflow</a>
      <a href="https://discuss.reactjs.org/" target="_blank">Discussion Forum</a>
      <a href="https://discord.gg/0ZcbPKXt5bZjGY5n" target="_blank">Reactiflux Chat</a>
      <a href="https://www.facebook.com/react" target="_blank">Facebook</a>
      <a href="https://twitter.com/reactjs" target="_blank">Twitter</a>
    </div>
    <div>
      <h5><a href="/react/community/support.html">Resources</a></h5>
      <a href="/react/community/conferences.html">Conferences</a>
      <a href="/react/community/videos.html">Videos</a>
      <a href="https://github.com/facebook/react/wiki/Examples" target="_blank">Examples</a>
      <a href="https://github.com/facebook/react/wiki/Complementary-Tools" target="_blank">Complementary Tools</a>
    </div>
    <div>
      <h5>More</h5>
      <a href="/react/blog/">Blog</a>
      <a href="https://github.com/facebook/react" target="_blank">GitHub</a>
      <a href="http://facebook.github.io/react-native/" target="_blank">React Native</a>
      <a href="/react/acknowledgements.html">Acknowledgements</a>
    </div>
  </section>
  <a href="https://code.facebook.com/projects/" target="_blank" class="fbOpenSource">
    <img src="/img/oss_logo.png" alt="Facebook Open Source" width="170" height="45"/>
  </a>
  <section class="copyright">
    Copyright © 2017 Facebook Inc.
  </section>
</footer>

  </div>

  <div id="fb-root"></div>
  <script src="/js/anchor-links.js"></script>
  <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
    ga('create', 'UA-41298772-1', 'facebook.github.io');
    ga('send', 'pageview');

    !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");

    (function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return;
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.6&appId=623268441017527";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

    docsearch({
      apiKey: '36221914cce388c46d0420343e0bb32e',
      indexName: 'react',
      inputSelector: '#algolia-doc-search'
    });
  </script>
</body>
</html>
